package com.leeall.google.auth;

import java.util.Properties;
import java.util.Set;
import java.util.Map.Entry;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;

import com.leeall.google.GoogleConstants;
import com.leeall.spring.utils.SpringContextLoader;
import com.leeall.utils.string.StringUtil;
import java.lang.reflect.Method;

/**
 * Manage application client login action use Google Account Auth.
 * @author Leeall (lixiaosong@gmail.com)
 */
public class AppsClientLogin {

    private static Logger logger = Logger.getLogger(AppsClientLogin.class);
    private HttpClient httpClient = new HttpClient(
            new MultiThreadedHttpConnectionManager());
    /**
     * Account Authentication URL
     */
    private String authUrl;

    /**
     * Applicatoin Login Actoin
     * @param accountType
     * @param email
     * @param passwd
     * @param service
     * @param source
     * @param logintoken
     * @param logincaptcha
     * @return  Login status
     */
    public boolean login(String accountType, String email, String passwd,
            String service, String source, String logintoken,
            String logincaptcha) {
        boolean status = false;
        PostMethod post = new PostMethod(this.getAuthUrl());
        post.addParameter("accountType", accountType);
        post.addParameter("Email", email);
        post.addParameter("Passwd", passwd);
        post.addParameter("service", service);
        post.addParameter("source", source);

        if (StringUtil.stringIsNotEmpty(logintoken)) {
            post.addParameter("logintoken", logintoken);
        }
        if (StringUtil.stringIsNotEmpty(logincaptcha)) {
            post.addParameter("logincaptcha", logincaptcha);
        }

        try {
            int rep = httpClient.executeMethod(post);
            if (rep == GoogleConstants.GOOGLE_AUTH_ACCOUNT_LOGIN_SUCCEED) {
                status = true;
            }
            Properties properties = new Properties();
            properties.load(post.getResponseBodyAsStream());
            Set<Entry<Object, Object>> entrySet = properties.entrySet();
            AuthSuccessResp resp = new AuthSuccessResp();
            for (Entry<Object, Object> entry : entrySet) {
                Method m = AuthSuccessResp.class.getMethod("set" + (String) entry.getKey(), String.class);
                m.invoke(resp, (String) entry.getValue());
            }
        } catch (Exception e) {
            logger.error("Client Login error", e);
        } finally {
            post.releaseConnection();
        }
        return status;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            AppsClientLogin appsClientLogin = (AppsClientLogin) SpringContextLoader.getBean("appsClientLogin");
            boolean status = appsClientLogin.login(
                    GoogleConstants.GOOGLE_AUTH_ACCOUNT_TYPE_GOOGLE,
                    "leeall.apps@gmail.com", "leeallapplication", "cl",
                    "leeall-jatalk-0.0.1", "", "");
            System.out.println("Login " + (status ? "Succeed" : "Failed"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getAuthUrl() {
        return authUrl;
    }

    public void setAuthUrl(String authUrl) {
        this.authUrl = authUrl;
    }
}
